<?php

namespace App\Http\Controllers\Services;

use App\Models\Organize;
use mysql_xdevapi\Exception;

class OrganizeService
{
    public static function index($pid = 0)
    {
        $where = [
            'pid' => $pid
        ];
        $organizes = Organize::where($where)->get();
        return $organizes;
    }

    public static function store($data)
    {
        self::existOrganizeName($data['organize_name']);
        $organize = new Organize();
        $organize->pid = $data['pid'];
        $organize->organize_name = $data['organize_name'];
        $organize->path = $data['path'];
        $result = $organize->save();
        return $result;
    }

    public static function getOrganizePath($pid = 0)
    {
        if ($pid) {
            $pOrganize = self::findOne($pid);
            $path = $pOrganize->path  . $pOrganize->id.',';
        } else {
            $path = ',0,';
        }
        return $path;
    }

    public static function update($id, $data)
    {
        $organize = self::findOne($id);
        $oldPid = $organize->pid;
        $oldOrganizeName = $organize->organize_name;
        dump($oldOrganizeName);
        if ($oldPid != $data['pid']) {
            if (!self::hasChild($id)) {
                $organize->pid = $data['pid'];
            }
        }
        if ($oldOrganizeName != $data['organize_name']) {
            if (!self::existOrganizeName($data['organize_name'])) {
                $organize->organize_name = $data['organize_name'];
            }
        }
        if ($oldPid != $data['pid'] || $oldOrganizeName != $data['organize_name']){
            $result = $organize->save();
        }else{
            $result = $organize;
        }
        return  $result;
    }

    public static function existOrganizeName($organizeName)
    {
        $where = [
            'organize_name' => $organizeName
        ];
        $organize = Organize::where($where)->get();
        if ($organize) {
            throw  new \Exception('组织名已经存在');
        }
        return false;
    }

    public static function findOne($pid)
    {
        $pOrganize = Organize::find($pid);
        if (!$pOrganize) {
            throw new \Exception('资源未找到');
        }
        return $pOrganize;
    }

    public static function hasChild($id)
    {
        $where = [
            'pid' => $id
        ];
        $organizeChildren = Organize::where($where)->get();
        // dd($organizeChildren);
        if (count($organizeChildren) >0) {
            throw new \Exception('该组织拥有子组织,不能修改上级组织');
        }
        return false;
    }
}
